/* The original version of this was taken from some blog I think. */
function tabHook(event, el) {
  if(event.keyCode == Event.KEY_TAB) {
    var replace = "  "; // Default to 2space softtab
    var oldscroll = el.scrollTop; //So the scroll won't move after a tabbing
    event.returnValue=false;  //This doesn't seem to help anything, maybe it helps for IE
    //Check if we're in a firefox deal
    if (el.setSelectionRange) {
      var pos_to_leave_caret = el.selectionStart + replace.length; // NOTE: if you want to insert "\t", change this to 5
      //Put in the tab
      el.value = el.value.substring(0,el.selectionStart) + replace + el.value.substring(el.selectionEnd,el.value.length);
      //There's no easy way to have the focus stay in the textarea, below seems to work though
      setTimeout(function() {
        el.focus(); el.setSelectionRange(pos_to_leave_caret, pos_to_leave_caret);
      }, 0);
    } else { // IE
      document.selection.createRange().text=replace;
    }
    el.scrollTop = oldscroll; //put back the scroll
  }
}

document.observe("dom:loaded", function() {
  if ($('snippet_content'))
    $('snippet_content').observe('keydown', function(e) { tabHook(e, $('snippet_content')); }, false);
  else if($('layout_content'))
    $('layout_content').observe('keydown', function(e) { tabHook(e, $('layout_content')); }, false);
});

